<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useStoreDict } from '@/store/modules/dict'
import { useAddMemberLevel, useGetRightAllPage } from '@fl/api/man-api'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { ElLoading } from 'element-plus'
import { cloneDeep } from 'lodash-es'

const flUpload = ref()

const { data: rightData, isLoading: rightLoading } = useGetRightAllPage()
const { isPending, mutate } = useAddMemberLevel()
const { dicts, init } = useStoreDict()
init(['member_validity'])

const rightIdsOptions = computed(() => {
    return rightData.value
        ? rightData.value.map((item: any) => {
            return {
                fieldItemProps: {
                    disabled: item.status === 0,
                },
                label: item.rightName,
                value: item.id,
            }
        })
        : []
})

const periodDayOptions = computed(() => {
    return dicts.member_validity
        ? dicts.member_validity.map((item: any) => {
            return {
                label: item.dictLabel,
                value: item.dictValue,
            }
        })
        : []
})

const visible = defineModel<boolean>('visible', { required: true })

const id = defineModel<any>('id')

const form = defineModel<any>('form')

const title = computed(() => id.value ? '编辑会员等级' : '添加会员等级')

const formRef = ref()

const state = ref<any>(
    {
        imageUrl: '',
        levelName: '',
        levelOrder: 0,
        periodDay: '',
        price: 0,
        rightIds: '',
        status: true,
    },
)

const columns = computed<PlusColumn[]>(() => {
    return [
        {
            colProps: {
                span: 24,
            },
            fieldProps: {
                maxlength: 50,
            },
            label: '等级名称',
            prop: 'levelName',
        },
        {
            colProps: {
                span: 24,
            },
            label: '背景图片',
            prop: 'imageUrl',
        },
        {
            colProps: {
                span: 24,
            },
            fieldProps: { max: 999999999, min: 0, precision: 2 },
            label: '费用标准',
            prop: 'price',
            valueType: 'input-number',
        },
        {
            colProps: {
                span: 24,
            },
            label: '有效期',
            options: periodDayOptions.value,
            prop: 'periodDay',
            valueType: 'select',
        },
        {
            colProps: {
                span: 24,
            },
            fieldProps: {
                multiple: true,

            },
            label: '会员权益',
            options: rightIdsOptions.value,
            prop: 'rightIds',
            valueType: 'select',
        },
        {
            colProps: {
                span: 24,
            },
            label: '等级状态',
            prop: 'status',
            valueType: 'switch',
        },
        {
            colProps: {
                span: 24,
            },
            fieldProps: { max: 999999999, min: 1, precision: 0 },
            label: '等级排序',
            prop: 'levelOrder',
            valueType: 'input-number',
        },
    ]
})

const rules = {
    imageUrl: [
        {
            message: '请上传背景图片',
            required: true,
        },
    ],
    levelName: [
        {
            message: '请输入等级名称',
            pattern: '[^ \x20]+',
            required: true,
        },
    ],
    periodDay: [
        {
            message: '请选择有效期',
            required: true,
        },
    ],
    rightIds: [
        {
            message: '请选择会员权益',
            required: true,
        },
    ],

}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    form.value = ''
    formRef.value.formInstance.resetFields()
}

async function save() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...unref(state),
            levelId: id.value,
            status: state.value.status ? 1 : 2,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function servicesLoading(node, str, lock, bg) {
    return ElLoading.service({
 	background: bg, // 背景色与透明度
        lock, // 同v-loading的修饰符
        // loading需要覆盖的DOM节点，默认为body
        target: document.querySelector(node),
        text: str, // 加载文案
    // spinner: 'el-icon-loading',	 //加载图标
    })
}

const uploadFileStatus = ref(false)
const loadingInstance = ref<any>(null)
function uploadFileStart() {
    uploadFileStatus.value = true
    loadingInstance.value = servicesLoading('.el-dialog.upload-file-dialog', '正在上传中,请耐心等待', true, 'rgba(0,0,0,0.3)')
}
function uploadSuccess(data: any) {
    if (data.url) {
        uploadFileStatus.value = false
        setTimeout(() => {
            loadingInstance.value.close()
            ElMessage.success('图片上传成功')
        }, 1000)
    }
}

watchEffect(() => {
    if (form.value) {
        const params = {
            ...form.value,
            status: form.value.status === 1,
        }
        state.value = cloneDeep(params)
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                @cancel="cancel"
                @closed="reset"
    >
        <el-skeleton v-if="rightLoading"
                     :rows="5"
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-imageUrl>
                <FlUpload ref="flUpload"
                          v-model="state.imageUrl"
                          is-mall-admin
                          accept=".jpg,.png,.jpeg"
                          @start="uploadFileStart"
                          @success="uploadSuccess"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="save"
                >
                    保存
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
